package com.zsc.newbuds.controller;

import com.zsc.newbuds.entity.Admin;
import com.zsc.newbuds.entity.User;
import com.zsc.newbuds.utils.OssUtil;
import com.zsc.newbuds.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 文件上传
 * @author D
 */
@Controller
public class UpLoadController {

    @Autowired
    RedisUtil redisUtil;

    @Autowired
    OssUtil ossUtil;

    @ResponseBody
    @PostMapping("/admin/upLoad")
    public String upLoad(@RequestParam("file") MultipartFile file, HttpSession session) throws IOException {
        System.out.println("上传");
        if(file==null){
            return "error";
        }else {
            Admin admin = (Admin)session.getAttribute("admin");
            ossUtil.upLoad(file,"admin",admin.getAdminId());
            String imgUrl = (String) redisUtil.get("headSculpture:admin"+admin.getAdminId().toString());
            System.out.println(imgUrl);
            session.setAttribute("img",imgUrl);
            return imgUrl;
        }
    }


    @PostMapping("/uploadImage")
    @ResponseBody
    public Map<String,Object> uploadImage(@RequestParam MultipartFile file,HttpSession session) throws IOException {
        //上传头像
        System.out.println(file);
        User user = (User) session.getAttribute("user");
        System.out.println(user);
        ossUtil.upLoad(file, "user", user.getUserId());
        String imgUrl = (String) redisUtil.get("headSculpture:user" + user.getUserId().toString());
        System.out.println(imgUrl);
        session.setAttribute("userImg",imgUrl);
        Map<String, Object> map = new HashMap<>();
        map.put("msg", "success");
        map.put("code", 0);
        map.put("link", imgUrl);
        return map;
    }
}
